package output

import "github.com/kataras/iris/v12"

const (
	StatusSuccess = 200 //成功
	StatusError   = 400 //失败
)

// Output 输出结构体
type Output struct {
	Code    int
	Message string
	Data    interface{}
	Ctx     iris.Context
}

// Success 输出成功
func Success(ctx iris.Context, data interface{}) {
	o := Output{
		Ctx: ctx,
	}
	o.Success(data)
}

// Success 输出成功
func (op *Output) Success(data interface{}) {
	if op.Code == 0 {
		op.Code = StatusSuccess
	}
	if op.Message == "" {
		op.Message = "ok"
	}
	op.Data = data

	op.OutJson()
}

// Error 输出标准错误
func Error(ctx iris.Context, message string) {
	o := Output{
		Ctx: ctx,
	}
	o.Error(message)
}

// Message 输出标准错误
func (op *Output) Error(message string) {
	if op.Code == 0 {
		op.Code = StatusError
	}
	op.Message = message

	op.OutJson()
}

func (op *Output) OutJson() {
	_, _ = (*op.Ctx).JSON(op.getAllData())
}

func (op *Output) getAllData() map[string]interface{} {
	data := make(map[string]interface{})
	data["message"] = op.Message
	data["code"] = op.Code
	data["data"] = op.Data

	return data
}
